package ArrayListExercise;

import java.util.Arrays;

public class MyArrayList implements IList{

    public int[] elem;
    public int usedSize;

    public MyArrayList() {
        elem=new int[10];
    }

    @Override
    public boolean isFull() {
        return usedSize==elem.length;
    }

    @Override
    public void add(int data) {
       if(isFull()) {
           elem= Arrays.copyOf(elem,2*elem.length);
       }
       elem[usedSize]=data;
       usedSize++;
    }

    public void checkPosLegal(int pos) {
        if(pos<0 || pos>usedSize) {
            throw new PosNotLegalException("add时pos位置不合法");
        }
    }

    @Override
    public void add(int pos, int data) throws PosNotLegalException{
        if(isFull()) {
            elem= Arrays.copyOf(elem,2*elem.length);
        }
        try{
            checkPosLegal(pos);
        }catch(PosNotLegalException e) {
            e.printStackTrace();
        }
        for(int i=usedSize;i>pos;i--) {
            elem[i]=elem[i-1];
        }
        elem[pos]=data;
        usedSize++;
    }

    public boolean contains(int value) {
        for(int i=0;i<usedSize;i++) {
            if(elem[i]==value) {
                return true;
            }
        }
        return false;
    }

    public int toFind(int value) {
        for(int i=0;i<usedSize;i++) {
            if(elem[i]==value) {
                return i;
            }
        }
        return -1;
    }

    public void checkPosOfGetAndSet(int pos) {
        if(pos<0 || pos>=usedSize) {
            throw new PosNotLegalException("get或set时pos位置不合法");
        }
    }

    @Override
    public int get(int pos) {
        try{
            checkPosOfGetAndSet(pos);
        }catch(PosNotLegalException e){
            e.printStackTrace();
        }
        return elem[pos];
    }

    @Override
    public void set(int pos, int value) {
        try{
            checkPosOfGetAndSet(pos);
        }catch(PosNotLegalException e){
            e.printStackTrace();
        }
        elem[pos]=value;
    }

    @Override
    public void remove(int toRemove) {
        
    }

    @Override
    public void clear() {
        usedSize=0;
    }

    @Override
    public void display() {
        for(int i=0;i<usedSize;i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }
}
